<script>
import ReviewApi from '@/api/review'
import MyPagination from '@/components/MyPagination.vue'
import { useUserStore } from '@/stores/user'

export default {
  name: 'UserReviewListView',
  components: {
    MyPagination,
  },
  data() {
    return {
      reviewList: [],
      total: 0,
      pageSize: 10,
      curPage: 1,
      loading: false,
      editMode: false,
      editingReview: null,
      editForm: {
        feedback: '',
        rating: 5
      }
    }
  },
  computed: {
    userStore() {
      return useUserStore()
    },
    userId() {
      console.log('User store state:', this.userStore);
      console.log('User data:', this.userStore.userData);
      return this.userStore.userData?.userId
    }
  },
  mounted() {
    console.log('Component mounted, user store state:', this.userStore);
    console.log('User data:', this.userStore.userData);
  },
  methods: {
    formatDate(dateString) {
      if (!dateString) return '';
      // 处理 ISO 格式的日期字符串
      if (dateString.includes('T')) {
        dateString = dateString.replace('T', ' ').split('.')[0];
      }
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return dateString; // 如果解析失败，返回原始字符串
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    async fetchReviews() {
      if (!this.userId) {
        console.log('Waiting for user data to be available...');
        return;
      }

      this.loading = true;
      try {
        const api = new ReviewApi()
        const offset = (this.curPage - 1) * this.pageSize;
        console.log('Fetching reviews for user:', this.userId);
        console.log('Page size:', this.pageSize, 'Offset:', offset);
        const res = await api.getUserReviewList(this.userId, this.pageSize, offset)
        console.log('API Response:', res);
        if (res.code === 200) {
          this.reviewList = res.data.list || []
          this.total = res.data.total || 0
          console.log('Updated review list:', this.reviewList);
          console.log('Total reviews:', this.total);
        } else {
          console.error('API Error:', res.msg);
          this.$myMessageBox(res.msg || '获取评论失败')
        }
      } catch (err) {
        console.error('Error fetching reviews:', err)
        this.$myMessageBox('获取评论失败，请稍后重试')
      } finally {
        this.loading = false;
      }
    },
    gotoPage(page) {
      this.curPage = page
      this.fetchReviews()
    },
    confirmDelete(reviewId) {
      if (confirm('确定要删除这条评论吗？')) {
        this.deleteReview(reviewId)
      }
    },
    async deleteReview(reviewId) {
      try {
        const api = new ReviewApi()
        const res = await api.deleteReview(reviewId)
        if (res.code === 200) {
          this.$myMessageBox('评论删除成功')
          this.fetchReviews() // 刷新列表
        } else {
          this.$myMessageBox(res.msg || '删除评论失败')
        }
      } catch (err) {
        console.error('Error deleting review:', err)
        this.$myMessageBox('删除评论失败，请稍后重试')
      }
    },
    startEdit(review) {
      this.editingReview = review;
      this.editForm = {
        feedback: review.feedback,
        rating: review.rating
      };
      this.editMode = true;
    },
    cancelEdit() {
      this.editMode = false;
      this.editingReview = null;
      this.editForm = {
        feedback: '',
        rating: 5
      };
    },
    async submitEdit() {
      if (!this.editForm.feedback.trim()) {
        this.$myMessageBox('评论内容不能为空');
        return;
      }
      if (this.editForm.rating < 1 || this.editForm.rating > 5) {
        this.$myMessageBox('评分必须在1-5之间');
        return;
      }

      try {
        const api = new ReviewApi();
        const res = await api.editReview(this.editingReview.id, this.editForm);
        if (res.code === 200) {
          this.$myMessageBox('评论更新成功');
          this.editMode = false;
          this.editingReview = null;
          this.fetchReviews(); // 刷新列表
        } else {
          this.$myMessageBox(res.msg || '更新评论失败');
        }
      } catch (err) {
        console.error('Error updating review:', err);
        this.$myMessageBox('更新评论失败，请稍后重试');
      }
    }
  },
  watch: {
    userId: {
      immediate: true,
      handler(newId) {
        if (newId) {
          this.fetchReviews();
        }
      }
    }
  }
}
</script>

<template>
  <div class="user-review-list-view w80">
    <h2>我的评论</h2>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else class="table-container">
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>设备名称</th>
            <th>评分</th>
            <th>评论内容</th>
            <th>发表时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="reviewList.length === 0">
            <td colspan="6" class="no-data">暂无评论数据</td>
          </tr>
          <template v-for="(review, index) in reviewList" :key="review.id">
            <tr v-if="editMode && editingReview?.id === review.id">
              <td colspan="6">
                <div class="edit-form">
                  <div class="form-group">
                    <label>评分：</label>
                    <select v-model="editForm.rating">
                      <option v-for="n in 5" :key="n" :value="n">{{ n }}星</option>
                    </select>
                  </div>
                  <div class="form-group">
                    <label>评论内容：</label>
                    <textarea v-model="editForm.feedback" rows="3"></textarea>
                  </div>
                  <div class="form-actions">
                    <button class="save-btn" @click="submitEdit">保存</button>
                    <button class="cancel-btn" @click="cancelEdit">取消</button>
                  </div>
                </div>
              </td>
            </tr>
            <tr v-else>
              <td>{{ (curPage - 1) * pageSize + index + 1 }}</td>
              <td>{{ review.deviceName }}</td>
              <td>{{ review.rating }}星</td>
              <td>{{ review.feedback }}</td>
              <td>{{ formatDate(review.createdTime) }}</td>
              <td>
                <button class="edit-btn" @click="startEdit(review)">编辑</button>
                <button class="delete-btn" @click="confirmDelete(review.id)">删除</button>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>
    <MyPagination
      :total="total"
      :pageSize="pageSize"
      :curPage="curPage"
      @goto="gotoPage"
      :showInfo="true"
    />
  </div>
</template>

<style scoped>
.user-review-list-view {
  padding: 20px;
  max-width: 80%;
  margin: 20px auto;
}

.table-container {
  margin-top: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

thead {
  background-color: #f8f8f8;
}

th {
  font-weight: bold;
  color: #333;
}

tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

tbody tr:hover {
  background-color: #f1f1f1;
}

.no-data {
  text-align: center;
  padding: 50px;
  color: #666;
}

.edit-btn,
.delete-btn {
  padding: 8px 12px;
  margin-right: 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.edit-btn {
  background-color: #007bff;
  color: white;
}

.edit-btn:hover {
  background-color: #0056b3;
}

.delete-btn {
  background-color: #dc3545;
  color: white;
}

.delete-btn:hover {
  background-color: #c82333;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.edit-form {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.save-btn,
.cancel-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.save-btn {
  background-color: #28a745;
  color: white;
}

.save-btn:hover {
  background-color: #218838;
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
}

.cancel-btn:hover {
  background-color: #5a6268;
}
</style> 